﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI.WebControls;
using Medianamik.Core;
using Medianamik.Core.Profile;
using Medianamik.Core.Security;
using Medianamik.Globalization;
using Medianamik.Globalization.Utilities;
using Medianamik.UI.Controls;
using Medianamik.UI.Web.Services;
using Roles = Medianamik.Core.Security.Roles;

namespace Medianamik.UI.ConfigManagement
{
    public partial class ResourceManagement : BasePage
    {
        protected MedianamikResourceDataManager Manager = new MedianamikResourceDataManager();

        private BaseModalWindow deleteWindow;
        private BaseModalWindow importWindow;
        private BaseModalWindow ExportWindow;
        private BaseModalWindow searchWindow;
        private BaseModalWindow addWindow;

        protected void lnkImportResX_OnClick(object sender, EventArgs e)
        {
            var converter = new ResXResourceConverter(Context.Request.PhysicalApplicationPath);
            converter.ImportWebResources();
            ShowMessage("Resource import completed.");

            lstResourceIds.SelectedValue = null;
            LoadResourceSets();
        }

        protected void lnkExportResX_OnClick(object sender, EventArgs e)
        {
            var exporter = new ResXResourceConverter(Context.Request.PhysicalApplicationPath);

            if (!exporter.GenerateLocalResourceResXFiles())
            {
                ShowError("Resource generation failed.");
                return;
            }
            if (!exporter.GenerateGlobalResourceResXFiles())
            {
                ShowError("Resource generation failed.");
                return;
            }

            ShowMessage("Resource generation completed.");
        }

        protected void Page_Init(object sender, EventArgs e)
        {
            deleteWindow = new BaseModalWindow
                            {
                                ID = "deleteWindow",
                                Width = Unit.Pixel(650),
                                Height = Unit.Pixel(200)
                            };
            MyWindowManager.Windows.Add(deleteWindow);

            importWindow = new BaseModalWindow
                            {
                                ID = "importWindow",
                                Width = Unit.Pixel(650),
                                Height = Unit.Pixel(500)
                            };
            MyWindowManager.Windows.Add(importWindow);

            ExportWindow = new BaseModalWindow
                                  {
                                      ID = "ExportWindow",
                                      Width = Unit.Pixel(700),
                                      Height = Unit.Pixel(500)
                                  };
            MyWindowManager.Windows.Add(ExportWindow);

            searchWindow = new BaseModalWindow
                            {
                                ID = "searchWindow",
                                Width = Unit.Pixel(800),
                                Height = Unit.Pixel(500)
                            };
            MyWindowManager.Windows.Add(searchWindow);

            addWindow = new BaseModalWindow
                        {
                            ID = "addWindow",
                            Width = Unit.Pixel(500),
                            Height = Unit.Pixel(350)
                        };
            MyWindowManager.Windows.Add(addWindow);

            var isAdmin = IsCurrentUserSuperAdmin;
            lnkExportResX.Visible = isAdmin;
            lnkImportResX.Visible = isAdmin;
        }

        private void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack)
            {
                if (!String.IsNullOrEmpty(Request[PostBack.PostBackEventTarget])
                && Request[PostBack.PostBackEventTarget].Equals(reloadType.ClientID)
                && !String.IsNullOrEmpty(Request[PostBack.PostBackEventArgument]))
                {
                    Reload(Request[PostBack.PostBackEventArgument]);
                }
            }
            else
            {
                if (Manager.IsLocalizationTable(null))
                {
                    phrMain.Visible = true;
                    LoadResourceSets();
                }
                else
                {
                    phrMain.Visible = false;
                    litError.Visible = true;
                    litError.Text = "SQL localization table (SQL) does not exist.";
                }
                txtSearchResources.Attributes.Add("onkeydown", "clickOnEnter(event, '" + btnSearchResources.ClientID + "')");
                btnSearchResources.OnClientClick = "openSearchWindow('" + txtSearchResources.ClientID + "')";
            }

            SetWindowParams();

            phLastContextUsed.Visible = MedianamikResourceConfiguration.Current.TrackLastContextUsed;

        }

        protected void lstResourceIds_SelectedIndexChanged(object sender, EventArgs e)
        {
            LoadResourceText();
        }

        protected void lstResourceSet_SelectedIndexChanged(object sender, EventArgs e)
        {
            LoadResourceIds();
        }

        protected override void OnCultureChanged(CultureChangedEventArgs e)
        {
            if (NonTranslatedOnly)
                LoadResourceSets();
            else
                LoadResourceText();
            upl.Update();
        }

        protected virtual void btnSave_Click(object sender, EventArgs e)
        {
            if (lstResourceIds.SelectedIndex >= 0 && lstResourceSet.SelectedIndex >= 0)
            {
                if (txtResource.Text.Trim().Length > 0)
                {
                    var resource = new Resource(lstResourceIds.SelectedValue, CurrentEditionCulture.Name,
                                                txtResource.Text, lstResourceSet.SelectedValue, null, ckLocalResource.Checked);
                    Manager.UpdateOrAdd(resource);
                }
                else
                    Manager.DeleteResource(lstResourceIds.SelectedValue, CurrentEditionCulture.Name, lstResourceSet.SelectedValue);
                ReloadResources();
            }
        }

        protected virtual void btnRefresh_Click(object sender, EventArgs e)
        {
            ReloadResources();
            string selectedResourceSet = lstResourceSet.SelectedValue;

            LoadResourceSets();

            if (lstResourceSet.Items.Count > 0)
            {
                if (lstResourceSet.Items.FindByValue(selectedResourceSet) == null)
                {
                    lstResourceSet.SelectedIndex = 0;
                }
                else
                {
                    lstResourceSet.SelectedValue = selectedResourceSet;
                }

                LoadResourceIds();
            }
            else
            {
                lstResourceIds.Items.Clear();
                txtResource.Text = "";
                ckLocalResource.Checked = false;
            }
            upl.Update();
        }

        protected void ChangeFilter(object sender, EventArgs e)
        {
            LoadResourceSets();
        }

        private IEnumerable<Culture> _editionCultures;
        public override IEnumerable<Culture> EditionCultures
        {
            get
            {
                if (_editionCultures == null)
                {
                    _editionCultures = ConfigManager.GetAllCultures()
                        .Where(c => c.CultureName != String.Empty)
                        .OrderBy(c => c.Position);
                }

                return _editionCultures;
            }
        }

        private bool NonTranslatedOnly
        {
            get
            {
                return Filters.SelectedValue == "notrans";
            }
        }

        private void LoadResourceSets()
        {
            var resourceType = IsCurrentUserSuperAdmin ? ResourceListingTypes.AllResources : ResourceListingTypes.NonSecuredOnly;

            var currentSet = lstResourceSet.SelectedValue;

            DataTable dt = NonTranslatedOnly
                         ? Manager.GetAllNonTranslatedResourceSets(CurrentEditionCulture, resourceType)
                         : Manager.GetAllResourceSets(resourceType);
            lstResourceSet.DataSource = dt;
            lstResourceSet.DataValueField = "ResourceSet";
            lstResourceSet.DataBind();
            try
            {
                lstResourceSet.SelectedValue = currentSet;
            }
            catch (ArgumentOutOfRangeException)
            {
                lstResourceSet.SelectedIndex = 0;
            }
            LoadResourceIds();
        }

        private void LoadResourceIds()
        {
            DataTable dt = NonTranslatedOnly
                         ? Manager.GetAllNonTranslatedResourceIds(lstResourceSet.SelectedValue, CurrentEditionCulture)
                         : Manager.GetAllResourceIds(lstResourceSet.SelectedValue);

            if (dt == null)
            {
                ShowError("Unable to receive resource ids from localization table (SQL).");
                return;
            }

            var previous = lstResourceIds.SelectedValue;

            lstResourceIds.DataSource = dt;
            lstResourceIds.DataValueField = "ResourceId";
            lstResourceIds.DataTextField = "ResourceId";
            lstResourceIds.DataBind();

            if (lstResourceIds.Items.Count > 0)
            {
                try
                {
                    lstResourceIds.SelectedValue = previous;
                }
                catch (ArgumentOutOfRangeException)
                {
                    lstResourceIds.SelectedIndex = 0;
                }
            }

            LoadResourceText();
        }

        private void LoadResourceText()
        {
            if (lstResourceIds.SelectedIndex >= 0 && lstResourceSet.SelectedIndex >= 0)
            {
                btnSave.Enabled = true;
                txtResource.Enabled = true;
                ckLocalResource.Enabled = true;
                lblCurrentResourceId.Text = lstResourceIds.SelectedValue;

                var resource = Manager.GetResource(lstResourceIds.SelectedValue,
                                                  lstResourceSet.SelectedValue, CurrentEditionCulture.Name);

                txtResource.Text = resource != null ? resource.Value : string.Empty;
                ckLocalResource.Checked = resource != null ? resource.Local.GetValueOrDefault() : false;

                if (MedianamikResourceConfiguration.Current.TrackLastContextUsed)
                    litLastContext.Text = Manager.GetResourceLastContext(lstResourceIds.SelectedValue, lstResourceSet.SelectedValue);

                var sets = Manager.GetResourceSets(ResourceListingTypes.InternalResourceOnly);
                if (!sets.Any(resourceSet => resourceSet.Equals(lstResourceSet.SelectedValue, StringComparison.OrdinalIgnoreCase)))
                {
                    ckLocalResource.Enabled = false;
                    ckLocalResource.Checked = false;
                }


                SetDeleteWindowUrl();
            }
            else
            {
                btnSave.Enabled = false;
                txtResource.Enabled = false;
                ckLocalResource.Enabled = false;
                txtResource.Text = String.Empty;
                ckLocalResource.Checked = false;
                lblCurrentResourceId.Text = string.Empty;
            }

            deleteLinkPanel.Update();
        }

        public void ReloadResources()
        {
            MedianamikResourceConfiguration.ClearResourceCache();

            //Reset du Menu
            ((MedianamikSiteMapProvider)SiteMap.Provider).Rebuild();
        }

        public void ShowMessage(string pMessage)
        {
            litError.Visible = true;
            litError.Text = pMessage;
        }

        public void ShowError(string pError)
        {
            phrMain.Visible = false;
            litError.Visible = true;
            litError.Text = pError;
        }

        private void SetDeleteWindowUrl()
        {
            lnkDelete.NavigateUrl = String
                .Format("/medianamik/modalwindows/DeleteResourceWindow.aspx?id={0}&culture={1}&set={2}",
                lstResourceIds.SelectedValue, CurrentEditionCulture.Name, lstResourceSet.SelectedValue);

            if (IsPostBack)
                deleteLinkPanel.Update();
        }

        void Reload(string type)
        {
            if (type.Equals("ReloadResourceIDs"))
            {
                LoadResourceIds();
            }
            else if (type.Equals("ReloadResourceSets"))
            {
                LoadResourceSets();
            }
            else if (type.Equals("ReloadValue"))
            {
                LoadResourceText();
            }
            else if (type.IndexOf("LoadResource") != -1)
            {
                var parts = type.Split(';');
                if (parts.Length == 3 && parts[0] == "LoadResource")
                {
                    if (Filters.SelectedValue == "notrans")
                    {
                        Filters.SelectedValue = "all";
                        LoadResourceSets();
                    }
                    var resourceSet = parts[1];
                    var resourceId = parts[2];
                    lstResourceSet.SelectedValue = resourceSet;
                    LoadResourceIds();
                    lstResourceIds.SelectedValue = resourceId;
                    LoadResourceText();
                }
            }
        }

        private void SetWindowParams()
        {
            deleteWindow.OnClientClose = "modalWindowCallback";
            deleteWindow.IconUrl = "/Medianamik/images/Icones/Ico_Supprimer.gif";
            deleteWindow.ReloadOnShow = true;
            deleteWindow.ShowContentDuringLoad = false;

            importWindow.OnClientClose = "modalWindowCallback";
            importWindow.IconUrl = "/Medianamik/images/Icones/Ico_Sauvegarder.gif";
            importWindow.ReloadOnShow = true;
            importWindow.ShowContentDuringLoad = false;

            ExportWindow.OnClientClose = "modalWindowCallback";
            ExportWindow.IconUrl = "/Medianamik/images/Icones/Ico_Sauvegarder.gif";
            ExportWindow.ReloadOnShow = true;
            ExportWindow.ShowContentDuringLoad = false;

            searchWindow.OnClientClose = "modalWindowCallback";
            searchWindow.IconUrl = "/Medianamik/images/Icones/Ico_Repertoire.gif";
            searchWindow.ReloadOnShow = true;
            searchWindow.ShowContentDuringLoad = false;

            addWindow.OnClientClose = "modalWindowCallback";
            addWindow.IconUrl = "/Medianamik/images/Icones/Ico_Plus.gif";
            addWindow.ReloadOnShow = true;
            addWindow.ShowContentDuringLoad = false;
        }

        protected void btnRefreshResourceSet_OnClick(object sender, EventArgs e)
        {
            var service = new ResourceService();
            var rSets = new[] { lstResourceSet.SelectedValue };

            service.UpdateResourceSetsFromService(rSets, false);
            LoadResourceIds();
        }
    }
}